#!/usr/bin/python
# -*- coding:utf-8 -*-

import sys
from opencv.cv import *
from opencv.highgui import *


class FaceDetector(object):
    def __init__(self, cascade_name = "faces.xml", input_name = 0,
                 window = "Medidor de Audiência", min_size = cvSize(50,50),
                 haar_scale = 2.0, min_neighbors = 2, haar_flags = 0):

        self.cascade = cvLoadHaarClassifierCascade( cascade_name, cvSize(1,1) )
        assert self.cascade, "Could not load classifier cascade"
        self.capture = cvCreateCameraCapture( input_name )
        assert self.capture, "Could not load capture"
        self.window = window
        self.min_size = min_size
        self.haar_scale = haar_scale
        self.min_neighbors = min_neighbors
        self.haar_flags = haar_flags
        self.storage = cvCreateMemStorage(0)
        self.frame = cvQueryFrame( self.capture )
            
    def show_window(self):
        cvNamedWindow(self.window, 1)
    
    def detect_and_draw(self):

        cvClearMemStorage(self.storage)

        faces = cvHaarDetectObjects(self.frame, self.cascade,
                    self.storage, self.haar_scale, 
                    self.min_neighbors, self.haar_flags, self.min_size)
        n = 0
        for r in faces or []:
            n += 1
            pt1 = cvPoint(r.x, r.y)
            pt2 = cvPoint(r.x+r.width, r.y+r.height)
            cvRectangle(self.frame, pt1, pt2, CV_RGB(255,0,0), 3, 8, 0)

        cvShowImage(self.window, self.frame)
        
        return n

    def loop(self, observer):
        while True:
            self.frame = cvQueryFrame(self.capture)

            f = self.detect_and_draw()

            observer.notify(f)

            if(cvWaitKey(10) >= 0):
                break

class SimplePeopleObserver(object):
    def __init__(self):
        self.total = 0
        self._nf = 0
    def notify (self, n):
        if n != self.total:
            self._nf += 1
            if self._nf > 5:
                self._nf = 0
                self.total = n
                self.update(n)
    def update(self,n):
        if n == 0:
            print "nenhuma detectada"
        elif n == 1:
            print "1 pessoaa detectada"
        else:
            print "%d pessoas detectadas"%n

if __name__ == '__main__':
    detector = FaceDetector()
    observer = SimplePeopleObserver()
    detector.show_window()
    detector.loop(observer)
